package org.dfzt.modules.online.cgform.controller;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.google.common.collect.Lists;
import org.dfzt.common.api.vo.Result;
import org.dfzt.common.aspect.annotation.OnlineAuth;
import org.dfzt.common.aspect.annotation.PermissionData;
import org.dfzt.common.system.service.ISysBaseAPI;
import org.dfzt.common.system.vo.DictModel;
import org.dfzt.common.util.SpringContextUtils;
import org.dfzt.common.util.TokenUtils;
import org.dfzt.common.util.oConvertUtils;
//import org.dfzt.modules.online.cgform.a.a;
//import org.dfzt.modules.online.cgform.converter.b;
import org.dfzt.modules.online.cgform.entity.OnlCgformButton;
import org.dfzt.modules.online.cgform.entity.OnlCgformEnhanceJs;
import org.dfzt.modules.online.cgform.entity.OnlCgformField;
import org.dfzt.modules.online.cgform.entity.OnlCgformHead;
import org.dfzt.modules.online.cgform.model.OnlGenerateModel;
import org.dfzt.modules.online.cgform.model.TreeModel;
import org.dfzt.modules.online.cgform.model.OnlComplexModel;
import org.dfzt.modules.online.cgform.service.IOnlCgformFieldService;
import org.dfzt.modules.online.cgform.service.IOnlCgformHeadService;
import org.dfzt.modules.online.cgform.service.IOnlCgformSqlService;
import org.dfzt.modules.online.cgform.service.IOnlineService;
import org.dfzt.modules.online.cgform.util.EnhanceJsUtil;
import org.dfzt.modules.online.cgform.util.b;
import org.dfzt.modules.online.config.exception.BusinessException;
import org.dfzt.modules.online.config.exception.DBException;
import org.dfzt.modules.online.config.util.d;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIncrementer;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@RestController("onlCgformApiController")
@RequestMapping({"/online/cgform/api"})
public class OnlCgformApiController {
  private static final Logger a = LoggerFactory.getLogger(OnlCgformApiController.class);


  @Autowired
  private IOnlCgformHeadService onlCgformHeadService;


  @Autowired
  private IOnlCgformFieldService onlCgformFieldService;

  @Autowired
  private IOnlCgformSqlService onlCgformSqlService;

  @Autowired
  private ISysBaseAPI sysBaseAPI;

  @Autowired
  private IOnlineService onlineService;

  @Value("${dfzt.path.upload}")
  private String upLoadPath;

  @Value("${dfzt.uploadType}")
  private String uploadType;


  @PostMapping({"/addAll"})
  public Result<?> a(@RequestBody org.dfzt.modules.online.cgform.model.OnlCgformModel parama) {
    try {
      String str = parama.getHead().getTableName();
      if (d.a(str).booleanValue()) {
        return Result.error("数据库表[" + str + "]已存在,请从数据库导入表单");
      }
      return this.onlCgformHeadService.addAll(parama);
    } catch (Exception exception) {
      a.error("OnlCgformApiController.addAll()发生异常：" + exception.getMessage(), exception);
      return Result.error("操作失败");
    }
  }

  @PutMapping({"/editAll"})
  public Result<?> b(@RequestBody org.dfzt.modules.online.cgform.model.OnlCgformModel parama) {
    try {
      return this.onlCgformHeadService.editAll(parama);
    } catch (Exception exception) {
      a.error("OnlCgformApiController.editAll()发生异常：" + exception.getMessage(), exception);
      return Result.error("操作失败");
    }
  }








  @OnlineAuth("getColumns")
  @GetMapping({"/getColumns/{code}"})
  public Result<OnlComplexModel> a(@PathVariable("code") String paramString) {
    Result result = new Result();
    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString);
    if (onlCgformHead == null) {
      result.error500("实体不存在");
      return result;
    }
    OnlComplexModel c = this.onlineService.queryOnlineConfig(onlCgformHead);
    result.setResult(c);
    return result;
  }







  @PermissionData
  @OnlineAuth("getData")
  @GetMapping({"/getData/{code}"})
  public Result<Map<String, Object>> a(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest) {
    Result result = new Result();
    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString);
    if (onlCgformHead == null) {
      result.error500("实体不存在");
      return result;
    }
    try {
      String str = onlCgformHead.getTableName();
      Map map1 = org.dfzt.modules.online.cgform.util.b.a(paramHttpServletRequest);
      Map map2 = this.onlCgformFieldService.queryAutolistPage(str, paramString, map1, null);
      a(onlCgformHead, map2);
      result.setResult(map2);
    } catch (Exception exception) {
      a.error(exception.getMessage(), exception);
      result.error500("数据库查询失败，" + exception.getMessage());
    }
    return result;
  }








  @OnlineAuth("getFormItem")
  @GetMapping({"/getFormItem/{code}"})
  public Result<?> b(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest) {
    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString);
    if (onlCgformHead == null) {
      Result.error("表不存在");
    }
    Result result = new Result();
    OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(paramString, "form");
    JSONObject jSONObject = this.onlineService.queryOnlineFormObj(onlCgformHead, onlCgformEnhanceJs);

    if (onlCgformHead.getTableType().intValue() == 2) {

      JSONObject jSONObject1 = jSONObject.getJSONObject("schema");
      String str = onlCgformHead.getSubTableStr();
      if (oConvertUtils.isNotEmpty(str)) {
        ArrayList<OnlCgformHead> arrayList = new ArrayList();
        for (String str1 : str.split(",")) {
          OnlCgformHead onlCgformHead1 = (OnlCgformHead)this.onlCgformHeadService.getOne((Wrapper)(new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, str1));
          if (onlCgformHead1 != null)
          {

            arrayList.add(onlCgformHead1); }
        }
        if (arrayList.size() > 0) {

          Collections.sort(arrayList, (param1OnlCgformHead1, param1OnlCgformHead2) -> {
            Integer integer1 = param1OnlCgformHead1.getTabOrderNum();
            if (integer1 == null) {
              integer1 = Integer.valueOf(0);
            }
            Integer integer2 = param1OnlCgformHead2.getTabOrderNum();
            if (integer2 == null) {
              integer2 = Integer.valueOf(0);
            }
            return integer1.compareTo(integer2);
          });

          for (OnlCgformHead onlCgformHead1 : arrayList) {

            List list1 = this.onlCgformFieldService.queryAvailableFields(onlCgformHead1.getId(), onlCgformHead1.getTableName(), null, false);


            EnhanceJsUtil.b(onlCgformEnhanceJs, onlCgformHead1.getTableName(), list1);

            JSONObject jSONObject2 = new JSONObject();

            List list2 = this.onlCgformFieldService.queryDisabledFields(onlCgformHead1.getTableName());

            if (1 == onlCgformHead1.getRelationType().intValue()) {

              jSONObject2 = org.dfzt.modules.online.cgform.util.b.a(list1, list2, null);
            } else {

              jSONObject2.put("columns", org.dfzt.modules.online.cgform.util.b.a(list1, list2));
            }
            jSONObject2.put("id", onlCgformHead1.getId());

            jSONObject2.put("describe", onlCgformHead1.getTableTxt());
            jSONObject2.put("key", onlCgformHead1.getTableName());
            jSONObject2.put("view", "tab");
            jSONObject2.put("order", onlCgformHead1.getTabOrderNum());
            jSONObject2.put("relationType", onlCgformHead1.getRelationType());
            jSONObject1.getJSONObject("properties").put(onlCgformHead1.getTableName(), jSONObject2);
          }
        }
      }


      if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
        jSONObject.put("enhanceJs", EnhanceJsUtil.a(onlCgformEnhanceJs.getCgJs()));
      }
    }
    result.setResult(jSONObject);
    return result;
  }






  @GetMapping({"/getFormItemBytbname/{table}"})
  public Result<?> a(@PathVariable("table") String paramString1, @RequestParam(name = "taskId", required = false) String paramString2) {
    Result result = new Result();
    LambdaQueryWrapper<OnlCgformHead> lambdaQueryWrapper = new LambdaQueryWrapper();
    lambdaQueryWrapper.eq(OnlCgformHead::getTableName, paramString1);
    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getOne(lambdaQueryWrapper);
    if (onlCgformHead == null) {
      Result.error("表不存在");
    }
    JSONObject jSONObject = new JSONObject();

    onlCgformHead.setTaskId(paramString2);
    jSONObject.put("schema", this.onlCgformHeadService.queryFormItem(onlCgformHead));
    jSONObject.put("head", onlCgformHead);
    result.setResult(jSONObject);
    return result;
  }

  @OnlineAuth("getEnhanceJs")
  @GetMapping({"/getEnhanceJs/{code}"})
  public Result<?> c(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest) {
    String str = "";
    OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(paramString, "form");
    if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs()))
    {
      str = EnhanceJsUtil.b(onlCgformEnhanceJs.getCgJs(), (List<OnlCgformButton>) null);
    }

    return Result.ok(str);
  }







  @GetMapping({"/form/{code}/{id}"})
  public Result<?> b(@PathVariable("code") String paramString1, @PathVariable("id") String paramString2) {
    try {
      Map map = this.onlCgformHeadService.queryManyFormData(paramString1, paramString2);
      return Result.ok(b.b(map));
    } catch (Exception exception) {
      a.error("Online表单查询异常：" + exception.getMessage(), exception);
      return Result.error("查询失败，" + exception.getMessage());
    }
  }







  @GetMapping({"/subform/{table}/{mainId}"})
  public Result<?> c(@PathVariable("table") String paramString1, @PathVariable("mainId") String paramString2) {
    try {
      Map map = this.onlCgformHeadService.querySubFormData(paramString1, paramString2);
      return Result.ok(b.b(map));
    } catch (Exception exception) {
      a.error("Online表单查询异常：" + exception.getMessage(), exception);
      return Result.error("查询失败，" + exception.getMessage());
    }
  }








  @GetMapping({"/subform/list/{table}/{mainId}"})
  public Result<?> d(@PathVariable("table") String paramString1, @PathVariable("mainId") String paramString2) {
    try {
      return Result.ok(this.onlCgformHeadService.queryManySubFormData(paramString1, paramString2));
    } catch (Exception exception) {
      a.error("Online表单查询异常：" + exception.getMessage(), exception);
      return Result.error("查询失败，" + exception.getMessage());
    }
  }











  @GetMapping({"/form/table_name/{tableName}/{dataId}"})
  public Result<?> e(@PathVariable("tableName") String paramString1, @PathVariable("dataId") String paramString2) {
    try {
      LambdaQueryWrapper<OnlCgformHead> lambdaQueryWrapper = new LambdaQueryWrapper();
      lambdaQueryWrapper.eq(OnlCgformHead::getTableName, paramString1);
      OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getOne(lambdaQueryWrapper);
      if (onlCgformHead == null) {
        throw new Exception("OnlCgform tableName: " + paramString1 + " 不存在！");
      }
      return b(onlCgformHead.getId(), paramString2);
    } catch (Exception exception) {
      a.error("Online表单查询异常，" + exception.getMessage(), exception);
      return Result.error("查询失败，" + exception.getMessage());
    }
  }







  @OnlineAuth("form")
  @PostMapping({"/form/{code}"})
  public Result<String> a(@PathVariable("code") String paramString, @RequestBody JSONObject paramJSONObject, HttpServletRequest paramHttpServletRequest) {
    Result result = new Result();
    try {
      String str1 = b.a();
      paramJSONObject.put("id", str1);
      String str2 = TokenUtils.getTokenByRequest(paramHttpServletRequest);
      this.onlCgformHeadService.saveManyFormData(paramString, paramJSONObject, str2);
      result.setSuccess(true);
      result.setResult(str1);
    } catch (Exception exception) {
      a.error("OnlCgformApiController.formAdd()发生异常：", exception);
      result.setSuccess(false);
      result.setMessage("保存失败，" + b.a(exception));
    }
    return result;
  }







  @OnlineAuth("form")
  @PutMapping({"/form/{code}"})
  public Result<?> a(@PathVariable("code") String paramString, @RequestBody JSONObject paramJSONObject) {
    try {
      this.onlCgformHeadService.editManyFormData(paramString, paramJSONObject);
    } catch (Exception exception) {
      a.error("OnlCgformApiController.formEdit()发生异常：" + exception.getMessage(), exception);
      return Result.error("修改失败，" + b.a(exception));
    }
    return Result.ok("修改成功！");
  }







  @OnlineAuth("form")
  @DeleteMapping({"/form/{code}/{id}"})
  public Result<?> f(@PathVariable("code") String paramString1, @PathVariable("id") String paramString2) {
    try {
      if (paramString2.indexOf(",") > 0) {

        OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString1);
        if (onlCgformHead == null) {
          return Result.error("实体不存在");
        }
        if (onlCgformHead.getTableType().intValue() == 2) {
          this.onlCgformFieldService.deleteAutoListMainAndSub(onlCgformHead, paramString2);
        } else {
          String str = onlCgformHead.getTableName();
          this.onlCgformFieldService.deleteAutoListById(str, paramString2);
        }
      } else {

        this.onlCgformHeadService.deleteOneTableInfo(paramString1, paramString2);
      }
    } catch (Exception exception) {
      a.error("OnlCgformApiController.formEdit()发生异常：" + exception.getMessage(), exception);
      return Result.error("删除失败");
    }
    return Result.ok("删除成功!");
  }









  @DeleteMapping({"/formByCode/{code}/{id}"})
  public Result<?> g(@PathVariable("code") String paramString1, @PathVariable("id") String paramString2) {
    try {
      OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getOne((Wrapper)(new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, paramString1));
      if (onlCgformHead == null) {
        return Result.error("实体不存在");
      }
      if (paramString2.indexOf(",") > 0) {

        String str = onlCgformHead.getTableName();
        this.onlCgformFieldService.deleteAutoListById(str, paramString2);
      } else {

        this.onlCgformHeadService.deleteOneTableInfo(onlCgformHead.getId(), paramString2);
      }
    } catch (Exception exception) {
      a.error("OnlCgformApiController.formEdit()发生异常：" + exception.getMessage(), exception);
      return Result.error("删除失败");
    }
    return Result.ok("删除成功!");
  }




  @OnlineAuth("getQueryInfo")
  @GetMapping({"/getQueryInfo/{code}"})
  public Result<?> b(@PathVariable("code") String paramString) {
    try {
      List list = this.onlCgformFieldService.getAutoListQueryInfo(paramString);
      return Result.ok(list);
    } catch (Exception exception) {
      a.error("OnlCgformApiController.getQueryInfo()发生异常：" + exception.getMessage(), exception);
      return Result.error("查询失败");
    }
  }




  @PostMapping({"/doDbSynch/{code}/{synMethod}"})
  public Result<?> h(@PathVariable("code") String paramString1, @PathVariable("synMethod") String paramString2) {
    try {
      long l = System.currentTimeMillis();
      this.onlCgformHeadService.doDbSynch(paramString1, paramString2);
      a.info("==同步数据库消耗时间" + (System.currentTimeMillis() - l) + "毫秒");
    } catch (Exception exception) {
      a.error(exception.getMessage(), exception);
      return Result.error("同步数据库失败，" + b.a(exception));
    }
    return Result.ok("同步数据库成功!");
  }










  @OnlineAuth("exportXls")
  @PermissionData
  @GetMapping({"/exportXls/{code}"})
  public void a(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse) {
    /*OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString);
    if (onlCgformHead == null) {
      return;
    }
    String str1 = onlCgformHead.getTableTxt();

    String str2 = paramHttpServletRequest.getParameter("paramsStr");
    Map map1 = new HashMap();
    String str3 = null;
    if (oConvertUtils.isNotEmpty(str2)) {
      try {
        str3 = URLDecoder.decode(str2, "UTF-8");
      } catch (UnsupportedEncodingException unsupportedEncodingException) {
        a.error(unsupportedEncodingException.getMessage(), unsupportedEncodingException);
      }
      if (str3 != null) {
        map1 = (Map)JSONObject.parseObject(str3, Map.class);
      }
    }

    map1.put("pageSize", Integer.valueOf(-521));
    Map<String, Object>  map2 = this.onlCgformFieldService.queryAutolistPage(onlCgformHead.getTableName(), onlCgformHead.getId(), map1, null);
    List list1 = (List)map2.get("fieldList");
    List<Map<String, Object>> list2 = (List)map2.get("records");
    List list3 = new ArrayList();

    String str4 = (map1.get("selections") == null) ? null : map1.get("selections").toString();
    if (oConvertUtils.isNotEmpty(str4)) {
      List list = Arrays.asList(str4.split(","));
      list3 = (List)list2.stream().filter(paramMap -> list.contains(paramMap.get("id"))).collect(Collectors.toList());
    } else {
      if (list2 == null) {
        list2 = new ArrayList();
      }
      list3.addAll(list2);
    }

    b.a(1, list3, list1);

    try {
      this.onlCgformHeadService.executeEnhanceExport(onlCgformHead, list3);
    } catch (BusinessException businessException) {
      a.error("导出java增强处理出错", businessException.getMessage());
    }



    List list4 = a(list1, "id");


    if (onlCgformHead.getTableType().intValue() == 2)
    {
      if (oConvertUtils.isEmpty(map1.get("exportSingleOnly"))) {
        String str = onlCgformHead.getSubTableStr();
        if (oConvertUtils.isNotEmpty(str)) {
          String[] arrayOfString = str.split(",");
          for (String str5 : arrayOfString) {
            a(str5, map1, list3, list4);
          }
        }
      }
    }


    Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, str1), list4, list3);

    object = null;
    try {
      paramHttpServletResponse.setContentType("application/x-msdownload;charset=utf-8");

      str5 = BrowserUtils.checkBrowse(paramHttpServletRequest);
      String str6 = onlCgformHead.getTableTxt() + "-v" + onlCgformHead.getTableVersion();
      if ("MSIE".equalsIgnoreCase(str5.substring(0, 4))) {
        paramHttpServletResponse.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(str6, "UTF-8") + ".xls");
      } else {
        String str = new String(str6.getBytes("UTF-8"), "ISO8859-1");
        paramHttpServletResponse.setHeader("content-disposition", "attachment;filename=" + str + ".xls");
      }

      ServletOutputStream servletOutputStream = paramHttpServletResponse.getOutputStream();
      workbook.write(servletOutputStream);
      paramHttpServletResponse.flushBuffer();
    } catch (Exception exception) {
      a.error("--通过流的方式获取文件异常--" + exception.getMessage(), exception);
    } finally {
      if (object != null) {
        try {
          object.close();
        } catch (IOException iOException) {
          a.error(iOException.getMessage(), iOException);
        }
      }
    } */
  }

  @OnlineAuth("importXls")
  @PostMapping({"/importXls/{code}"})
  public Result<?> b(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse) {
    long l = System.currentTimeMillis();
    Result result = new Result();
    String str = "";

    try {
      OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString);
      if (onlCgformHead == null) {
        return Result.error("数据库不存在该表记录");
      }

      LambdaQueryWrapper<OnlCgformField> lambdaQueryWrapper = new LambdaQueryWrapper();
      lambdaQueryWrapper.eq(OnlCgformField::getCgformHeadId, paramString);
      List list1 = this.onlCgformFieldService.list(lambdaQueryWrapper);
      String str1 = paramHttpServletRequest.getParameter("isSingleTableImport");

      List list2 = b.e(list1);
      if (oConvertUtils.isEmpty(str1) && onlCgformHead.getTableType().intValue() == 2 && oConvertUtils.isNotEmpty(onlCgformHead.getSubTableStr())) {
        for (String str4 : onlCgformHead.getSubTableStr().split(",")) {
          OnlCgformHead onlCgformHead1 = (OnlCgformHead)this.onlCgformHeadService.getOne((Wrapper)(new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, str4));
          if (onlCgformHead1 != null) {


            List list3 = this.onlCgformFieldService.list((Wrapper)(new LambdaQueryWrapper<OnlCgformField>()).eq(OnlCgformField::getCgformHeadId, onlCgformHead1.getId()));
            List list4 = b.b(list3, onlCgformHead1.getTableTxt());
            if (list4.size() > 0) {
              list2.addAll(list4);
            }
          }
        }
      }
      JSONObject jSONObject = null;
      String str2 = paramHttpServletRequest.getParameter("foreignKeys");
      if (oConvertUtils.isNotEmpty(str2)) {
        jSONObject = JSONObject.parseObject(str2);
      }
      MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)paramHttpServletRequest;
      Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();

      DataSource dataSource = (DataSource) SpringContextUtils.getApplicationContext().getBean(DataSource.class);
      String str3 = d.a(dataSource);
      for (Map.Entry entry : map.entrySet()) {
        MultipartFile multipartFile = (MultipartFile)entry.getValue();
        ImportParams importParams = new ImportParams();
        importParams.setImageList(list2);
        importParams.setDataHanlder(new org.dfzt.modules.online.cgform.util.OnlineExcelDataHandler(list1, this.upLoadPath, this.uploadType));
        List<Map> list = ExcelImportUtil.importExcel(multipartFile.getInputStream(), Map.class, importParams);
        if (list == null) {
          str = "识别模版数据错误";
          a.error(str); continue;
        }
        String str4 = "";
        ArrayList arrayList = new ArrayList();
        for (Map map1 : list) {
          Object object = null;
          boolean bool = false;
          Set<String> set = map1.keySet();
          HashMap hashMap = new HashMap();
          for (String str5 : set) {
            if (str5.indexOf("$subTable$") == -1) {
              if (str5.indexOf("$mainTable$") != -1 && oConvertUtils.isNotEmpty(map1.get(str5).toString())) {
                bool = true;

                object = a(onlCgformHead, dataSource, str3);
              }
              hashMap.put(str5.replace("$mainTable$", ""), map1.get(str5));
            }
          }
          if (bool) {


            hashMap.put("id", object);


            arrayList.add(hashMap);
            object = hashMap.get("id");
          }

          if (jSONObject != null) {
            for (String str5 : jSONObject.keySet()) {
              System.out.println(str5 + "=" + jSONObject.getString(str5));
              hashMap.put(str5, jSONObject.getString(str5));
            }
          }
          map1.put("$mainTable$id", object);
        }
        if (arrayList == null || arrayList.size() == 0) {
          result.setSuccess(false);
          result.setMessage("导入失败，匹配的数据条数为零!");
          return result;
        }
        this.onlCgformSqlService.saveBatchOnlineTable(onlCgformHead, list1, arrayList);



        if (oConvertUtils.isEmpty(str1) && onlCgformHead.getTableType().intValue() == 2 && oConvertUtils.isNotEmpty(onlCgformHead.getSubTableStr())) {
          for (String str5 : onlCgformHead.getSubTableStr().split(",")) {

            OnlCgformHead onlCgformHead1 = (OnlCgformHead)this.onlCgformHeadService.getOne((Wrapper)(new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, str5));
            if (onlCgformHead1 != null) {


              LambdaQueryWrapper<OnlCgformField> lambdaQueryWrapper1 = new LambdaQueryWrapper();
              lambdaQueryWrapper1.eq(OnlCgformField::getCgformHeadId, onlCgformHead1.getId());
              List<OnlCgformField> list3 = this.onlCgformFieldService.list(lambdaQueryWrapper1);
              ArrayList arrayList1 = new ArrayList();


              String str6 = onlCgformHead1.getTableTxt();
              for (Map map1 : list) {

                boolean bool = false;
                HashMap hashMap = new HashMap();
                for (OnlCgformField onlCgformField : list3) {

                  String str7 = onlCgformField.getMainTable();

                  String str8 = onlCgformField.getMainField();
                  boolean bool1 = (onlCgformHead.getTableName().equals(str7) && oConvertUtils.isNotEmpty(str8)) ? true : false;
                  String str9 = str6 + "_" + onlCgformField.getDbFieldTxt();

                  if (bool1) {
                    hashMap.put(onlCgformField.getDbFieldName(), map1.get("$mainTable$" + str8));
                  }
                  Object object = map1.get("$subTable$" + str9);
                  if (null != object && oConvertUtils.isNotEmpty(object.toString())) {
                    bool = true;
                    hashMap.put(onlCgformField.getDbFieldName(), object);
                  }
                }

                if (bool) {


                  hashMap.put("id", a(onlCgformHead1, dataSource, str3));
                  arrayList1.add(hashMap);
                }
              }


              if (arrayList1.size() > 0) {
                this.onlCgformSqlService.saveBatchOnlineTable(onlCgformHead1, list3, arrayList1);
              }
            }
          }
        }
        str = "文件导入成功！";
      }

      result.setSuccess(true);
      result.setMessage("导入成功!");
    } catch (Exception exception) {
      result.setSuccess(false);
      result.setMessage(exception.getMessage());
      a.error(exception.getMessage(), exception);
    }





















    a.info("=====online导入数据完成,耗时:" + (System.currentTimeMillis() - l) + "毫秒=====");
    return result;
  }





  @PostMapping({"/doButton"})
  public Result<?> a(@RequestBody JSONObject paramJSONObject) {
    String str1 = paramJSONObject.getString("formId");
    String str2 = paramJSONObject.getString("dataId");
    String str3 = paramJSONObject.getString("buttonCode");

    JSONObject jSONObject = paramJSONObject.getJSONObject("uiFormData");
    try {
      this.onlCgformHeadService.executeCustomerButton(str3, str1, str2);
    } catch (Exception exception) {
      a.error(exception.getMessage(), exception);
      return Result.error("执行失败!");
    }
    return Result.ok("执行成功!");
  }











  public Object a(OnlCgformHead paramOnlCgformHead, DataSource paramDataSource, String paramString) throws SQLException, DBException {
    String str1 = null;
    String str2 = paramOnlCgformHead.getIdType();
    String str3 = paramOnlCgformHead.getIdSequence();
    if (oConvertUtils.isNotEmpty(str2) && "UUID".equalsIgnoreCase(str2)) {
      str1 = b.a();
    } else if (oConvertUtils.isNotEmpty(str2) && "NATIVE".equalsIgnoreCase(str2)) {
      if (oConvertUtils.isNotEmpty(paramString) && "oracle".equalsIgnoreCase(paramString)) {
        OracleSequenceMaxValueIncrementer oracleSequenceMaxValueIncrementer = new OracleSequenceMaxValueIncrementer(paramDataSource, "HIBERNATE_SEQUENCE");
        try {
          str1 = String.valueOf(oracleSequenceMaxValueIncrementer.nextLongValue());
        } catch (Exception exception) {
          a.error(exception.getMessage(), exception);
        }
      } else if (oConvertUtils.isNotEmpty(paramString) && "postgres".equalsIgnoreCase(paramString)) {
        PostgreSQLSequenceMaxValueIncrementer postgreSQLSequenceMaxValueIncrementer = new PostgreSQLSequenceMaxValueIncrementer(paramDataSource, "HIBERNATE_SEQUENCE");
        try {
          str1 = String.valueOf(postgreSQLSequenceMaxValueIncrementer.nextLongValue());
        } catch (Exception exception) {
          a.error(exception.getMessage(), exception);
        }
      } else {
        str1 = null;
      }
    } else if (oConvertUtils.isNotEmpty(str2) && "SEQUENCE".equalsIgnoreCase(str2)) {
      if (oConvertUtils.isNotEmpty(paramString) && "oracle".equalsIgnoreCase(paramString)) {
        OracleSequenceMaxValueIncrementer oracleSequenceMaxValueIncrementer = new OracleSequenceMaxValueIncrementer(paramDataSource, str3);
        try {
          str1 = String.valueOf(oracleSequenceMaxValueIncrementer.nextLongValue());
        } catch (Exception exception) {
          a.error(exception.getMessage(), exception);
        }
      } else if (oConvertUtils.isNotEmpty(paramString) && "postgres".equalsIgnoreCase(paramString)) {
        PostgreSQLSequenceMaxValueIncrementer postgreSQLSequenceMaxValueIncrementer = new PostgreSQLSequenceMaxValueIncrementer(paramDataSource, str3);
        try {
          str1 = String.valueOf(postgreSQLSequenceMaxValueIncrementer.nextLongValue());
        } catch (Exception exception) {
          a.error(exception.getMessage(), exception);
        }
      } else {
        str1 = null;
      }
    } else {
      str1 = b.a();
    }
    return str1;
  }






  private void a(Map paramMap, List<OnlCgformField> paramList) {
    for (OnlCgformField onlCgformField : paramList) {
      String str1 = onlCgformField.getDictTable();
      String str2 = onlCgformField.getDictField();
      String str3 = onlCgformField.getDictText();
      if (oConvertUtils.isEmpty(str1) && oConvertUtils.isEmpty(str2)) {
        continue;
      }

      if (!"popup".equals(onlCgformField.getFieldShowType())) {
        List<DictModel> list;
        String str = String.valueOf(paramMap.get(onlCgformField.getDbFieldName()));
        if (oConvertUtils.isEmpty(str1)) {
          list = this.sysBaseAPI.queryDictItemsByCode(str2);
        } else {
          list = this.sysBaseAPI.queryTableDictItemsByCode(str1, str3, str2);
        }
        for (DictModel dictModel : list) {
          if (str.equals(dictModel.getText())) {
            paramMap.put(onlCgformField.getDbFieldName(), dictModel.getValue());
          }
        }
      }
    }
  }








  private List<ExcelExportEntity> a(List<OnlCgformField> paramList, String paramString) {
    ArrayList arrayList = new ArrayList();
    for (byte b = 0; b < paramList.size(); b++) {
      if (null == paramString || !paramString.equals(((OnlCgformField)paramList.get(b)).getDbFieldName()))
      {

        if (((OnlCgformField)paramList.get(b)).getIsShowList().intValue() == 1) {
          String str = ((OnlCgformField)paramList.get(b)).getDbFieldName();
          ExcelExportEntity excelExportEntity = new ExcelExportEntity(((OnlCgformField)paramList.get(b)).getDbFieldTxt(), str);
          if ("image".equals(((OnlCgformField)paramList.get(b)).getFieldShowType())) {
            excelExportEntity.setType(2);
            excelExportEntity.setExportImageType(3);
            excelExportEntity.setImageBasePath(this.upLoadPath);
            excelExportEntity.setHeight(50.0D);
            excelExportEntity.setWidth(60.0D);
          } else {
            int b1 = (((OnlCgformField)paramList.get(b)).getDbLength().intValue() == 0) ? 12 : ((((OnlCgformField)paramList.get(b)).getDbLength().intValue() > 30) ? 30 : ((OnlCgformField)paramList.get(b)).getDbLength().intValue());
            if (((OnlCgformField)paramList.get(b)).getFieldShowType().equals("date")) {
              excelExportEntity.setFormat("yyyy-MM-dd");
            } else if (((OnlCgformField)paramList.get(b)).getFieldShowType().equals("datetime")) {
              excelExportEntity.setFormat("yyyy-MM-dd HH:mm:ss");
            }
            if (b1 < 10) {
              b1 = 10;
            }
            excelExportEntity.setWidth(b1);
          }











          arrayList.add(excelExportEntity);
        }  }
    }
    return arrayList;
  }









  private void a(String paramString, Map<String, Object> paramMap, List<Map<String, Object>> paramList1, List<ExcelExportEntity> paramList2) {
    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getOne((Wrapper)(new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, paramString));
    LambdaQueryWrapper<OnlCgformField> lambdaQueryWrapper = new LambdaQueryWrapper<OnlCgformField>();
    lambdaQueryWrapper.eq(OnlCgformField::getCgformHeadId, onlCgformHead.getId());
    lambdaQueryWrapper.orderByAsc(OnlCgformField::getOrderNum);
    List<OnlCgformField> list = this.onlCgformFieldService.list(lambdaQueryWrapper);
    String str1 = "", str2 = "";
    for (OnlCgformField onlCgformField : list) {
      if (oConvertUtils.isNotEmpty(onlCgformField.getMainField())) {
        str1 = onlCgformField.getMainField();
        str2 = onlCgformField.getDbFieldName();
        break;
      }
    }
    ExcelExportEntity excelExportEntity = new ExcelExportEntity(onlCgformHead.getTableTxt(), paramString);
    excelExportEntity.setList(a(list, "id"));
    paramList2.add(excelExportEntity);

    for (byte b = 0; b < paramList1.size(); b++) {
      paramMap.put(str2, ((Map)paramList1.get(b)).get(str1));
      String str = org.dfzt.modules.online.cgform.util.b.a(onlCgformHead.getTableName(), list, paramMap);
      a.info("-----------动态列表查询子表sql》》" + str);
      List list1 = this.onlCgformHeadService.queryListData(str);

      org.dfzt.modules.online.cgform.converter.b.a(1, list1, list);

      ((Map)paramList1.get(b)).put(paramString, org.dfzt.modules.online.cgform.util.b.d(list1));
    }
  }







  @GetMapping({"/checkOnlyTable"})
  public Result<?> i(@RequestParam("tbname") String paramString1, @RequestParam("id") String paramString2) {
    if (oConvertUtils.isEmpty(paramString2)) {
      if (d.a(paramString1).booleanValue()) {
        return Result.ok(Integer.valueOf(-1));
      }
    } else {
      OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString2);
      if (!paramString1.equals(onlCgformHead.getTableName()) &&
        d.a(paramString1).booleanValue()) {
        return Result.ok(Integer.valueOf(-1));
      }
    }

    return Result.ok(Integer.valueOf(1));
  }




  @PostMapping({"/codeGenerate"})
  public Result<?> b(@RequestBody JSONObject paramJSONObject) {
    OnlGenerateModel onlGenerateModel = (OnlGenerateModel)JSONObject.parseObject(paramJSONObject.toJSONString(), OnlGenerateModel.class);
    onlGenerateModel.setJspMode("one");
    onlGenerateModel.setJformType("1");
    List list = null;
    try {
      if ("1".equals(onlGenerateModel.getJformType())) {

        list = this.onlCgformHeadService.generateCode(onlGenerateModel);
      } else {

        list = this.onlCgformHeadService.generateOneToMany(onlGenerateModel);
      }
      return Result.ok(list);
    } catch (Exception exception) {
      exception.printStackTrace();
      return Result.error(exception.getMessage());
    }
  }





  @GetMapping({"/downGenerateCode"})
  public void a(@RequestParam("fileList") List<String> paramList, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse) {
    List list = (List)paramList.stream().filter(paramString -> (paramString.indexOf("src/main/java") == -1 && paramString.indexOf("src%5Cmain%5Cjava") == -1)).collect(Collectors.toList());
    if (paramList == null || (list != null && list.size() > 0)) {
      a.error(" fileList 不合法！！！", paramList);
      return;
    }
    String str1 = "生成代码_" + System.currentTimeMillis() + ".zip";
    String str2 = "/opt/temp/codegenerate/" + str1;
    File file = org.dfzt.modules.online.cgform.util.d.a(paramList, str2);

    if (file.exists()) {
      paramHttpServletResponse.setContentType("application/force-download");
      paramHttpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + str1);
      byte[] arrayOfByte = new byte[1024];
      FileInputStream fileInputStream = null;
      BufferedInputStream bufferedInputStream = null;
      try {
        fileInputStream = new FileInputStream(file);
        bufferedInputStream = new BufferedInputStream(fileInputStream);
        ServletOutputStream servletOutputStream = paramHttpServletResponse.getOutputStream();
        int i = bufferedInputStream.read(arrayOfByte);
        while (i != -1) {
          servletOutputStream.write(arrayOfByte, 0, i);
          i = bufferedInputStream.read(arrayOfByte);
        }
      } catch (Exception exception) {
        exception.printStackTrace();
      } finally {
        if (bufferedInputStream != null) {
          try {
            bufferedInputStream.close();
          } catch (IOException iOException) {
            iOException.printStackTrace();
          }
        }
        if (fileInputStream != null) {
          try {
            fileInputStream.close();
          } catch (IOException iOException) {
            iOException.printStackTrace();
          }
        }
        //todo 为什么要删文件？furao
        /*(new Thread(this, str2) {
            @Override
            public void run() {
              try {
                sleep(10000L);

                FileUtil.del(this.);
              } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
              }
            }
          }).start();*/
      }
    }
  }


  @GetMapping({"/getTreeData/{code}"})
  @PermissionData
  public Result<Map<String, Object>> d(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest) {
    Result result = new Result();
    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString);
    if (onlCgformHead == null) {
      result.error500("实体不存在");
      return result;
    }
    try {
      String str1 = onlCgformHead.getTableName();
      String str2 = onlCgformHead.getTreeIdField();
      String str3 = onlCgformHead.getTreeParentIdField();

      ArrayList arrayList = Lists.newArrayList(new String[] { str2, str3 });
      Map map1 = b.a(paramHttpServletRequest);

      String str4 = null;
      if (map1.get(str2) != null) {
        str4 = map1.get(str2).toString();
      }
      if (map1.get(str3) == null || "0".equals(map1.get(str3))) {

        map1.put(str3, "0");
      } else {

        map1.put("pageSize", Integer.valueOf(-521));
        map1.put(str3, map1.get(str3));
      }
      map1.put(str2, null);
      Map map2 = this.onlCgformFieldService.queryAutolistPage(str1, paramString, map1, arrayList);


      if (map1.get(str3) != null) {
        String str = map1.get(str3).toString();
        if (!"0".equals(map1.get(str3)))
        {
          if (map2.get("total") != null && Integer.parseInt(map2.get("total").toString()) == 0)
          {
            if (str4 != null && "1".equals(str4))
            {
              this.onlCgformFieldService.updateTreeNodeNoChild(str1, str2, str);
            }
          }
        }
      }

      a(onlCgformHead, map2);
      result.setResult(map2);
    } catch (Exception exception) {
      a.error(exception.getMessage(), exception);
      result.error500("数据库查询失败" + exception.getMessage());
    }
    return result;
  }







  private void a(OnlCgformHead paramOnlCgformHead, Map<String, Object> paramMap) throws BusinessException {
    List list = (List)paramMap.get("records");
    this.onlCgformHeadService.executeEnhanceList(paramOnlCgformHead, "query", list);
  }








  @PostMapping({"/crazyForm/{name}"})
  public Result<?> b(@PathVariable("name") String paramString, @RequestBody JSONObject paramJSONObject) {
    Result result = new Result();
    try {
      String str = b.a();
      paramJSONObject.put("id", str);
      this.onlCgformHeadService.addCrazyFormData(paramString, paramJSONObject);
      result.setResult(str);
      result.setMessage("保存成功");
    } catch (Exception exception) {
      a.error("OnlCgformApiController.formAddForDesigner()发生异常：" + exception.getMessage(), exception);
      return Result.error("保存失败");
    }
    return result;
  }


  @PutMapping({"/crazyForm/{name}"})
  public Result<?> c(@PathVariable("name") String paramString, @RequestBody JSONObject paramJSONObject) {
    try {
      this.onlCgformHeadService.editCrazyFormData(paramString, paramJSONObject);
    } catch (Exception exception) {
      a.error("OnlCgformApiController.formEditForDesigner()发生异常：" + exception.getMessage(), exception);
      return Result.error("保存失败");
    }
    return Result.ok("保存成功!");
  }





  @GetMapping({"/getErpColumns/{code}"})
  public Result<Map<String, Object>> c(@PathVariable("code") String paramString) {
    Result result = new Result();
    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString);
    if (onlCgformHead == null) {
      result.error500("实体不存在");
      return result;
    }
    HashMap hashMap = new HashMap();
    OnlComplexModel c = this.onlineService.queryOnlineConfig(onlCgformHead);
    hashMap.put("main", c);
    if ("erp".equals(onlCgformHead.getThemeTemplate()) && onlCgformHead.getTableType().intValue() == 2) {

      String str = onlCgformHead.getSubTableStr();
      if (oConvertUtils.isNotEmpty(str)) {
        ArrayList arrayList = new ArrayList();
        for (String str1 : str.split(",")) {
          OnlCgformHead onlCgformHead1 = (OnlCgformHead)this.onlCgformHeadService.getOne((Wrapper)(new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, str1));
          if (onlCgformHead1 != null)
          {

            arrayList.add(this.onlineService.queryOnlineConfig(onlCgformHead1)); }
        }
        if (arrayList.size() > 0) {
          hashMap.put("subList", arrayList);
        }
      }
    }
    result.setResult(hashMap);
    result.setSuccess(true);
    return result;
  }








  @GetMapping({"/getErpFormItem/{code}"})
  public Result<?> e(@PathVariable("code") String paramString, HttpServletRequest paramHttpServletRequest) {
    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getById(paramString);
    if (onlCgformHead == null) {
      Result.error("表不存在");
    }
    Result result = new Result();
    JSONObject jSONObject = this.onlineService.queryOnlineFormObj(onlCgformHead);
    result.setResult(jSONObject);
    return result;
  }





  @GetMapping({"/querySelectOptions"})
  public Result<List<TreeModel>> a(@ModelAttribute org.dfzt.modules.online.cgform.link.LinkDown parama) {
    Result result = new Result();
    List list = this.onlCgformFieldService.queryDataListByLinkDown(parama);
    result.setResult(list);
    result.setSuccess(true);
    return result;
  }
}
